package com.example.calculate;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.Stack;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        setButtonWidth();
    }

    public void addZeroToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        if (currentText.indexOf("=") != -1)
            textView.setText(currentText);
        else
            textView.setText(currentText + "0");
    }

    public void addOneToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        if (currentText.indexOf("=") != -1)
            textView.setText("1");
        else
            textView.setText(currentText + "1");
    }

    public void addTwoToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        if (currentText.indexOf("=") != -1)
            textView.setText("2");
        else
            textView.setText(currentText + "2");
    }

    public void addThreeToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        if (currentText.indexOf("=") != -1)
            textView.setText("3");
        else
            textView.setText(currentText + "3");
    }

    public void addFourToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        if (currentText.indexOf("=") != -1)
            textView.setText("4");
        else
            textView.setText(currentText + "4");
    }

    public void addFiveToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        if (currentText.indexOf("=") != -1)
            textView.setText("5");
        else
            textView.setText(currentText + "5");
    }

    public void addSixToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        if (currentText.indexOf("=") != -1)
            textView.setText("6");
        else
            textView.setText(currentText + "6");
    }

    public void addSevenToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        if (currentText.indexOf("=") != -1)
            textView.setText("7");
        else
            textView.setText(currentText + "7");
    }

    public void addEightToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        if (currentText.indexOf("=") != -1)
            textView.setText("8");
        else
            textView.setText(currentText + "8");
    }

    public void addNineToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        if (currentText.indexOf("=") != -1)
            textView.setText("9");
        else
            textView.setText(currentText + "9");
    }

    public void addLeftBracketToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        textView.setText(currentText + "(");
    }

    public void addRightBracketToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        textView.setText(currentText + ")");
    }

    public void addAddToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        textView.setText(currentText + "+");
    }

    public void addMinusToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        textView.setText(currentText + "-");
    }

    public void addMultiToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        textView.setText(currentText + "*");
    }

    public void addDivideToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();
        textView.setText(currentText + "/");
    }

    public void backspaceInTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();

        char[] t = currentText.toCharArray();
        String tar = "";
        for (int i = 0; i < currentText.length() - 1; i++) {
            tar += t[i];
        }
        textView.setText(tar);
    }

    public void clearTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        textView.setText("");
    }

    public void printAnswerToTextView(View view) {
        TextView textView = findViewById(R.id.screen);
        String currentText = textView.getText().toString();

        try {
            String t = String.valueOf(calculateExpression(currentText));
            textView.setText(currentText + "=" + t);
        } catch (Exception e) {
            String url = "https://zhuanlan.zhihu.com/p/152339000";
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
        }
    }


    // 表达式求值
    public static double calculateExpression(String expression) throws IllegalArgumentException {
        if (expression == null || expression.isEmpty()) {
            throw new IllegalArgumentException("Invalid expression");
        }

        expression = expression.replaceAll("\\s", ""); // 去掉表达式中的空格

        Stack<Double> operands = new Stack<>();
        Stack<Character> operators = new Stack<>();

        for (int i = 0; i < expression.length(); i++) {
            char c = expression.charAt(i);

            if (Character.isDigit(c)) {
                StringBuilder sb = new StringBuilder();
                while (i < expression.length() && (Character.isDigit(expression.charAt(i)) || expression.charAt(i) == '.')) {
                    sb.append(expression.charAt(i));
                    i++;
                }
                i--;
                double operand = Double.parseDouble(sb.toString());
                operands.push(operand);
            } else if (c == '(') {
                operators.push(c);
            } else if (c == ')') {
                while (operators.peek() != '(') {
                    processOperator(operators, operands);
                }
                operators.pop();
            } else if (c == '+' || c == '-' || c == '*' || c == '/') {
                while (!operators.isEmpty() && precedence(operators.peek()) >= precedence(c)) {
                    processOperator(operators, operands);
                }
                operators.push(c);
            } else {
                throw new IllegalArgumentException("Invalid expression");
            }
        }

        while (!operators.isEmpty()) {
            processOperator(operators, operands);
        }

        if (operands.size() != 1 || !operators.isEmpty()) {
            throw new IllegalArgumentException("Invalid expression");
        }

        return operands.pop();
    }

    private static void processOperator(Stack<Character> operators, Stack<Double> operands) {
        char operator = operators.pop();
        double operand2 = operands.pop();
        double operand1 = operands.pop();
        double result = 0.0;
        switch (operator) {
            case '+':
                result = operand1 + operand2;
                break;
            case '-':
                result = operand1 - operand2;
                break;
            case '*':
                result = operand1 * operand2;
                break;
            case '/':
                result = operand1 / operand2;
                break;
        }
        operands.push(result);
    }

    private static int precedence(char operator) {
        if (operator == '+' || operator == '-') {
            return 1;
        } else if (operator == '*' || operator == '/') {
            return 2;
        } else {
            return 0; // '('
        }
    }// end 表达式求值


    public void setButtonWidth() {
        // 将 buttoon 宽度设置为屏幕1/4
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int screenWidth = displayMetrics.widthPixels;
        int buttonWidth = screenWidth / 4;  // 计算屏幕宽度的四分之一

        Button button1 = findViewById(R.id.num0);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.num1);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.num2);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.num3);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.num3);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.num4);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.num5);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.num6);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.num7);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.num8);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.num9);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.opAdd);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.opMinus);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.opMulti);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.opDivide);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.opLeftBracket);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.opRightBracket);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.opEqual);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.funBackspace);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);

        button1 = findViewById(R.id.funClear);
        layoutParams = (RelativeLayout.LayoutParams) button1.getLayoutParams();
        layoutParams.width = buttonWidth;
        button1.setLayoutParams(layoutParams);
    }
}